package config

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
)

/* 数据库连接配置 */
var username = "root"
var password = "XXXXX"
var host = "localhost"
var port = 3307
var dbname = "XXXX"

/* 全部变量便于服务层调用 */
var Db *gorm.DB

func ConnectToDatabase() *gorm.DB {
	// Set up the database source string.
	dataSourceName := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", username, password, host, port, dbname)

	// Create a database handle and open a connection pool.
	Db, err := gorm.Open(mysql.Open(dataSourceName), &gorm.Config{})
	if err != nil {
		log.Fatal(err)
	}
	// Check if our connection is alive.
	err = Db.Error
	if err != nil {
		log.Fatal(err)
	}
	return Db
}
func GetDB() *gorm.DB {
	if Db == nil {
		Db = ConnectToDatabase()
	}
	return Db
}
